package com.rpc.protocol.http;

import com.rpc.register.LocalRegister;
import org.apache.commons.io.IOUtils;
import com.rpc.framework.Invocation;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ObjectInputStream;
import java.lang.reflect.Method;

/**
 * @Author:cxy
 * @Date:2021/1/21 21:09
 */
public class HttpServerHandler {

    public void handle(HttpServletRequest request, HttpServletResponse response){
        try {
//            Invocation invocation = JSONObject.parseObject(request.getInputStream(), Invocation.class);
            ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
            Invocation invocation = (Invocation)ois.readObject();
//             spring 获取到Bean
            final Class<?> implClass = LocalRegister.get(invocation.getInterfaceName());
//            执行方法
            final Method method = implClass.getMethod(invocation.getMethodName(), invocation.getParamType());
            String invoke = (String)method.invoke(implClass.newInstance(), invocation.getParams());
            IOUtils.write(invoke,response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
